const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
  constructor(fn) {
    this.status = PENDING
    this.value = undefined
    this.reason = undefined
    // 收集执行成功和失败时的回调函数
    this.successCallback = []
    this.failCallback = []

    try {
      fn(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }

  resolve(value) {
    if (this.status === FULFILLED) return
    this.status = FULFILLED
    this.value = value
    while (this.successCallback.length) {
      this.successCallback.shift()()
    }
  }

  reject(reason) {
    if (this.status === REJECTED) return
    this.status = REJECTED
    this.reason = reason
    while (this.failCallback.length) {
      this.failCallback.shift()()
    }
  }

  then(successCallback, failCallback) {
    if (this.status === FULFILLED) {
      setTimeout(() => {
        successCallback(this.value)
      }, 0)
    } else if (this.status === REJECTED) {
      setTimeout(() => {
        failCallback(this.reason)
      }, 0)
    } else {
      successCallback = successCallback ? successCallback : value => value
      failCallback = failCallback ? failCallback : reason => reason

      
    }
  }
}

// 扩展 Promise - 进度, notify 方法来通知进度
class PromiseNotify extends Promise {
  constructor (callback) {
    let self
    super((resolve, reject) => {
      callback(resolve, reject, value => self.notify(value))
      return self
    })
    self = this
    console.log(this);
  }

  notify(value) {
    console.log(value, this);
    return this
  }
}

let p = new PromiseNotify((resolve) => {
  console.log(1111);
})
p.notify(1).notify(2).notify(3)
